#include "GemClient.h"

#define GEM_WIDTH 12.0

sf::Packet& operator >>(sf::Packet& packet, GemClient& gem) {
	int col;
	packet >> gem.position.x >> gem.position.y 
		>> col >> gem.points >> gem.picked;

	gem.colour = (GemColour)col;

	return packet;
}

GemClient::GemClient(GemColour col) {
	picked = false;
	points = 0;
	colour = col;
	
	sequence = 0;
	//vitesseMove = sf::milliseconds(100);
	chronoTime.restart();
	vitesseMove = sf::milliseconds(150);


	/* Initialisation des matrices*/
	sf::Vector2f matriceTemp[4] = {
		sf::Vector2f(2, 2),
		sf::Vector2f(18, 2),
		sf::Vector2f(34, 2),
		sf::Vector2f(50, 2),
	};
	memcpy(textureSequence, matriceTemp, sizeof(sf::Vector2f) * 4);

	std::string filename = "../Img/gems/gem_";
	std::string extension;

	switch (colour) {
	case YELLOW :
		extension = "yellow.png";
		break;

	case BLUE :
		extension = "blue.png";
		break;

	case GREEN :
		extension = "green.png";
		break;

	case GREY :
		extension = "grey.png";
		break;

	case RED :
		extension = "red.png";
		break;

	case PURPLE :
		extension = "purple.png";
		break;

	default :
		break;
	}

	if (!gemTexture.loadFromFile(filename + extension)) {
		printf("Erreur au chargement de la texture\n");
	}
}

void GemClient::draw(sf::RenderWindow& w) {
	if (!picked) {
		sprite.setTexture(gemTexture, true);
		sprite.setTextureRect(sf::IntRect(textureSequence[sequence].x,
		textureSequence[sequence].y, GEM_WIDTH, GEM_WIDTH));

		/* Place le sprite a la position du gem */
		sprite.setOrigin(GEM_WIDTH/2, GEM_WIDTH/2); 
		sprite.setPosition(position.x, position.y);

		w.draw(sprite);
	}
}

void GemClient::receive(sf::TcpSocket& socket) {
		sf::Packet packet;

		socket.receive(packet);
		packet >> *this;
}

void GemClient::animation() {	
	time = chronoTime.getElapsedTime();
		
	//Calcul du temps avant de passer a l'image suivante
	if(time > vitesseMove) {
		incSequence();
		chronoTime.restart();
	}
}

void GemClient::incSequence() {
	sequence++;

	if (sequence == 4) {
		sequence = 0;
	}
}
